package com.mst.controller;

import com.mst.config.UploadProperty;
import com.mst.core.Result;
import com.mst.domain.User;
import com.mst.service.IUserService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author 马松涛
 */
@RestController
@AllArgsConstructor
@RequestMapping
public class LoginController {
    private final UploadProperty uploadProperty;
    private IUserService userService;

    @PostMapping("/login")
    public Result<User> login(String username, String password, HttpSession session, HttpServletResponse response) {
        User user = userService.login(username, password);
        session.setAttribute("user", user);
        return Result.success(user);
    }

    //    @PostMapping("/register")
//    public Result register(@RequestBody User user) {
//        return Result.success(userService.register(user));
//    }
    @PostMapping("/register")
    public Result<User> register(MultipartFile file, User user) {
//        如果文件不是空的,代表用户上传了文件
        if (!file.isEmpty()) {
//            获取原始文件名
            String originalFilename = file.getOriginalFilename();
//            获取文件类型
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
//            定义限制上传文件类型的数组
            List<String> supportSuffix = Arrays.asList(".png", ".jpg");
//            如果用户上传的文件没有包含在限制里面
            if (!supportSuffix.contains(suffix)) {
                return Result.error(500, "头像格式只支持,png和jpg!");
            }
//            最终文件名
            String filename = "avatar/" + System.currentTimeMillis() + "-" + originalFilename;
            try {
                file.transferTo(new File(uploadProperty.getLocalPath() + filename));
                user.setAvatar(filename);
            } catch (IOException e) {
                return Result.error(500, "上传失败");
            }
        }
        userService.register(user);
        return Result.success(user);
    }
}
